// pages/index/index.js
const util = require('../../utils/util')

Page({
  data: {
    userInfo: null,
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    drivers: [],
    dispatchers: []
  },

  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    this.checkLogin()
    this.loadDrivers()
    this.loadDispatchers()
  },

  // 检查登录状态
  checkLogin() {
    const app = getApp()
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    }
  },

  // 获取司机列表
  async loadDrivers() {
    try {
      const res = await util.request('/drivers')
      if (res.code === 200) {
        this.setData({
          drivers: res.data
        })
      }
    } catch (error) {
      console.error('获取司机列表失败:', error)
    }
  },

  // 获取调车人列表
  async loadDispatchers() {
    try {
      const res = await util.request('/dispatchers')
      if (res.code === 200) {
        this.setData({
          dispatchers: res.data
        })
      }
    } catch (error) {
      console.error('获取调车人列表失败:', error)
    }
  },

  // 获取用户信息
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        getApp().globalData.userInfo = res.userInfo
        this.login(res.userInfo)
      }
    })
  },

  // 微信登录
  async login(userInfo) {
    try {
      util.showLoading('登录中...')
      
      // 获取登录凭证
      const loginRes = await new Promise((resolve, reject) => {
        wx.login({
          success: resolve,
          fail: reject
        })
      })

      // 发送登录请求到后端
      const res = await util.request('/wx-login', {
        method: 'POST',
        data: {
          code: loginRes.code,
          userInfo: userInfo
        }
      })

      if (res.code === 200) {
        getApp().globalData.token = res.data.token
        getApp().globalData.userInfo = res.data.userInfo
        util.showToast('登录成功', 'success')
      } else {
        util.showToast(res.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      util.showToast('登录失败，请重试')
    } finally {
      util.hideLoading()
    }
  },

  // 创建用车记录
  createRecord() {
    if (!this.data.hasUserInfo) {
      util.showToast('请先登录')
      return
    }
    wx.navigateTo({
      url: '/pages/create-record/create-record'
    })
  },

  // 查看用车记录
  viewRecords() {
    wx.switchTab({
      url: '/pages/record/record'
    })
  },

  // 查询司机信息
  async queryDriver() {
    if (this.data.drivers.length === 0) {
      util.showToast('暂无司机信息')
      return
    }

    const driverNames = this.data.drivers.map(driver => driver.name)
    
    wx.showActionSheet({
      itemList: driverNames,
      success: async (res) => {
        const selectedDriver = this.data.drivers[res.tapIndex]
        try {
          const result = await util.request(`/driver-info?name=${selectedDriver.name}`)
          if (result.code === 200) {
            const driver = result.data
            wx.showModal({
              title: '司机信息',
              content: `姓名：${driver.name}\n车型：${driver.car_type}\n车牌：${driver.license_plate}\n电话：${driver.phone}`,
              showCancel: false
            })
          } else {
            util.showToast(result.message || '查询失败')
          }
        } catch (error) {
          util.showToast('查询失败，请重试')
        }
      }
    })
  }
})